<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="PersonId_FormItem" prop="PersonId">
							<template #label>
								<WtmLabelTooltip label="员工" tooltip="打卡人员" />
							</template>
							<el-select v-model="searchData.PersonId" :data="stateData.AllSysPersons" clearable>
								<el-option v-for="item in stateData.AllSysPersons" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
							</el-select>
						</el-form-item>
					</el-col> -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="StaffNo_FormItem" prop="StaffNo">
							<template #label>
								<WtmLabelTooltip label="工号" tooltip="员工工号" />
							</template>
							<el-input v-model="searchData.StaffNo" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="PunchTime_FormItem" prop="PunchTime">
							<template #label>
								<WtmLabelTooltip label="打卡时间" tooltip="打卡时间范围" />
							</template>
							<el-date-picker type="daterange" v-model="searchData.PunchTime" clearable></el-date-picker>
						</el-form-item>
					</el-col>

					<!-- 可展开的详细搜索条件 -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="DeviceName_FormItem" prop="DeviceName">
								<template #label>
									<WtmLabelTooltip label="设备名称" tooltip="考勤设备名称" />
								</template>
								<el-input v-model="searchData.DeviceName" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Location_FormItem" prop="Location">
								<template #label>
									<WtmLabelTooltip label="打卡地点" tooltip="打卡地理位置" />
								</template>
								<el-input v-model="searchData.Location" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="PunchType_FormItem" prop="PunchType">
								<template #label>
									<WtmLabelTooltip label="打卡类型" tooltip="打卡类型" />
								</template>
								<el-input v-model="searchData.PunchType" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="RecognitionType_FormItem" prop="RecognitionType">
								<template #label>
									<WtmLabelTooltip label="识别方式" tooltip="识别方式" />
								</template>
								<el-input v-model="searchData.RecognitionType" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ProcessStatus_FormItem" prop="ProcessStatus">
								<template #label>
									<WtmLabelTooltip label="处理状态" tooltip="记录处理状态" />
								</template>
								<el-input v-model="searchData.ProcessStatus" clearable></el-input>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysAttendanceRawRecord/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysAttendanceRawRecord/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysAttendanceRawRecord/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysAttendanceRawRecord/ExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
			<WtmButton icon="fa fa-refresh" type="success" button-text="同步打卡记录" @click="onSyncHikVisionClick()" />
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysAttendanceRawRecord/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysAttendanceRawRecord/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysAttendanceRawRecord/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>

		<!-- 同步对话框 -->
		<el-dialog
			v-model="syncDialogVisible"
			width="520px"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			class="sync-dialog"
			align-center
		>
			<template #header>
				<div class="dialog-header">
					<div class="header-icon">
						<el-icon size="24" color="#409eff">
							<Refresh />
						</el-icon>
					</div>
					<div class="header-content">
						<h3 class="dialog-title">同步海康威视打卡记录</h3>
						<p class="dialog-subtitle">选择需要同步的时间范围</p>
					</div>
				</div>
			</template>

			<div class="sync-dialog-content">
				<div class="sync-options-container">
					<div
						v-for="option in syncOptions"
						:key="option.value"
						class="sync-option-card"
						:class="{ 'is-selected': selectedSyncDays === option.value }"
						@click="selectedSyncDays = option.value"
					>
						<div class="option-radio">
							<el-radio :label="option.value" v-model="selectedSyncDays" />
						</div>
						<div class="option-content">
							<div class="option-title">{{ option.label }}</div>
							<div class="option-description">{{ option.description }}</div>
						</div>
						<div class="option-indicator">
							<el-icon v-if="selectedSyncDays === option.value" color="#409eff">
								<Check />
							</el-icon>
						</div>
					</div>
				</div>

				<transition name="fade-slide">
					<div v-if="selectedSyncDays" class="date-preview-card">
						<div class="preview-header">
							<el-icon color="#67c23a">
								<Calendar />
							</el-icon>
							<span class="preview-title">同步范围预览</span>
						</div>
						<div class="preview-content">
							<div class="date-range">{{ getDateRangeText() }}</div>
							<div class="sync-tip">
								<el-icon size="14" color="#909399">
									<InfoFilled />
								</el-icon>
								<span>数据将从海康威视系统同步到本地数据库</span>
							</div>
						</div>
					</div>
				</transition>
			</div>

			<template #footer>
				<div class="dialog-footer">
					<el-button size="large" @click="syncDialogVisible = false"> 取消 </el-button>
					<el-button type="primary" size="large" @click="handleSyncConfirm" :loading="syncLoading" :disabled="!selectedSyncDays">
						<el-icon v-if="!syncLoading" style="margin-right: 6px">
							<Download />
						</el-icon>
						{{ syncLoading ? '正在同步...' : '开始同步' }}
					</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="打卡记录;true;HengTong.Areas.Hr.Controllers;SysAttendanceRawRecord">
import ElMessage from 'element-plus/es/components/message/index';
import { ElMessageBox } from 'element-plus';
import { Refresh, Check, Calendar, InfoFilled, Download } from '@element-plus/icons-vue';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed, h } from 'vue';
import { SysAttendanceRawRecordApi as api } from '/@/views/hr/sysattendancerawrecord/api';
import { ISysAttendanceRawRecordView, ISysAttendanceRawRecordQuery } from '/@/views/hr/sysattendancerawrecord/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysAttendanceRawRecordQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({
	AllSysPersons: [] as ISysSelectType[],
});

const searchData = ref<ISysAttendanceRawRecordQuery>({
	PersonId: null,
	StaffNo: null,
	PunchTime: null,
	DeviceName: null,
	Location: null,
	PunchType: null,
	RecognitionType: null,
	ProcessStatus: null,
});

// 同步对话框相关变量
const syncDialogVisible = ref(false);
const selectedSyncDays = ref('1');
const syncLoading = ref(false);

// 同步选项配置
const syncOptions = [
	{
		value: '1',
		label: '1天',
		description: '同步昨天的打卡数据',
	},
	{
		value: '3',
		label: '3天',
		description: '同步最近3天的打卡数据',
	},
	{
		value: '5',
		label: '5天',
		description: '同步最近5天的打卡数据',
	},
	{
		value: '7',
		label: '7天',
		description: '同步最近7天的打卡数据',
	},
];

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）
	// 按优先级排列：核心信息 > 打卡信息 > 设备信息 > 处理信息 > 技术详情
	header: [
		// 【最高优先级】核心识别信息
		{ title: '工号', key: 'StaffNo', type: 'text', isCheck: true },
		{ title: '打卡时间', key: 'PunchTime', type: 'text', isCheck: true },

		// 【高优先级】打卡关键信息
		{ title: '打卡类型', key: 'PunchType', type: 'text', isCheck: true },
		{ title: '识别方式', key: 'RecognitionType', type: 'text', isCheck: true },
		{ title: '打卡地点', key: 'Location', type: 'text', isCheck: true },

		// 【中等优先级】设备和处理信息
		{ title: '设备名称', key: 'DeviceName', type: 'text', isCheck: true },
		{ title: '处理状态', key: 'ProcessStatus', type: 'text', isCheck: true },

		// 【较低优先级】详细技术信息（默认隐藏）
		{ title: '设备号', key: 'DeviceId', type: 'text', isCheck: false },
		{ title: '处理时间', key: 'ProcessTime', type: 'text', isCheck: false },
		{ title: '备注', key: 'Remark', type: 'text', isCheck: false },

		// 【最低优先级】地理坐标和原始数据（默认隐藏）
		{ title: '经度', key: 'Longitude', type: 'text', isCheck: false },
		{ title: '纬度', key: 'Latitude', type: 'text', isCheck: false },
		{ title: '原始数据', key: 'RawData', type: 'text', isCheck: false },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		// 处理时间范围：将 PunchTime 数组转换为 PunchTimeStart 和 PunchTimeEnd
		const queryData = { ...searchData.value };
		await tableRef.value.doSearch(api().search, queryData);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysAttendanceRawRecordView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysAttendanceRawRecordView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysAttendanceRawRecordView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysAttendanceRawRecordView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 同步海康威视打卡记录 - 显示对话框
const onSyncHikVisionClick = () => {
	syncDialogVisible.value = true;
};

// 获取日期范围文本
const getDateRangeText = () => {
	const days = parseInt(selectedSyncDays.value);
	const endDate = new Date();
	endDate.setDate(endDate.getDate() - 1); // 昨天

	const startDate = new Date(endDate);
	startDate.setDate(startDate.getDate() - (days - 1)); // 往前推 days-1 天

	const formatDate = (date: Date) => date.toISOString().split('T')[0];

	if (days === 1) {
		return `将同步：${formatDate(endDate)}（昨天）的数据`;
	} else {
		return `将同步：${formatDate(startDate)} 至 ${formatDate(endDate)}（最近${days}天）的数据`;
	}
};

// 处理同步确认
const handleSyncConfirm = async () => {
	try {
		syncLoading.value = true;
		const days = parseInt(selectedSyncDays.value);

		// 计算日期范围（从昨天开始往前推）
		const endDate = new Date();
		endDate.setDate(endDate.getDate() - 1); // 昨天

		const startDate = new Date(endDate);
		startDate.setDate(startDate.getDate() - (days - 1)); // 往前推 days-1 天

		const syncData = {
			startDate: startDate.toISOString().split('T')[0],
			endDate: endDate.toISOString().split('T')[0],
		};

		// 显示同步信息
		if (days === 1) {
			ElMessage.info(`开始同步昨天的打卡记录数据（${syncData.endDate}）`);
		} else {
			ElMessage.info(`开始同步${days}天的打卡记录数据（${syncData.startDate} 至 ${syncData.endDate}）`);
		}

		// 关闭对话框
		syncDialogVisible.value = false;

		// 显示加载状态
		loading.value = true;
		ElMessage.info('正在同步海康威视打卡记录，请稍候...');

		// 调用同步API
		const response = await api().syncHikVisionAttendance(syncData);

		if (response?.Code === 200) {
			ElMessage.success(`同步成功！${response.Message || '已完成打卡记录同步'}`);
			// 刷新表格数据
			await getTableData();
		} else {
			ElMessage.error(`同步失败：${response?.Message || '未知错误'}`);
		}
	} catch (error: any) {
		console.error('同步海康威视打卡记录失败:', error);
		ElMessage.error(`同步失败：${error.message || '网络错误，请稍后重试'}`);
	} finally {
		syncLoading.value = false;
		loading.value = false;
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [
		other.getSelectList('/api/SysAttendanceRawRecord/GetSysPersons', [], false).then((x) => (stateData.AllSysPersons = x)),

		getTableData(),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>

<style scoped>
/* 同步对话框整体样式 */
:deep(.sync-dialog) {
	border-radius: 16px;
	overflow: hidden;
}

:deep(.sync-dialog .el-dialog__header) {
	padding: 0;
	border-bottom: 1px solid #f0f0f0;
}

:deep(.sync-dialog .el-dialog__body) {
	padding: 24px;
}

:deep(.sync-dialog .el-dialog__footer) {
	padding: 16px 24px;
	border-top: 1px solid #f0f0f0;
	background-color: #fafafa;
}

/* 对话框头部样式 */
.dialog-header {
	display: flex;
	align-items: center;
	padding: 20px 24px;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
}

.header-icon {
	margin-right: 16px;
	padding: 8px;
	background-color: rgba(255, 255, 255, 0.2);
	border-radius: 12px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.header-content {
	flex: 1;
}

.dialog-title {
	margin: 0 0 4px 0;
	font-size: 18px;
	font-weight: 600;
	color: white;
}

.dialog-subtitle {
	margin: 0;
	font-size: 14px;
	color: rgba(255, 255, 255, 0.8);
	font-weight: 400;
}

/* 同步选项容器 */
.sync-dialog-content {
	padding: 0;
}

.sync-options-container {
	display: flex;
	flex-direction: column;
	gap: 12px;
	margin-bottom: 24px;
}

/* 选项卡片样式 */
.sync-option-card {
	display: flex;
	align-items: center;
	padding: 16px 20px;
	border: 2px solid #e4e7ed;
	border-radius: 12px;
	background-color: #fff;
	cursor: pointer;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	position: relative;
	overflow: hidden;
}

.sync-option-card::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(135deg, rgba(64, 158, 255, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
	opacity: 0;
	transition: opacity 0.3s ease;
}

.sync-option-card:hover {
	border-color: #409eff;
	transform: translateY(-2px);
	box-shadow: 0 8px 25px rgba(64, 158, 255, 0.15);
}

.sync-option-card:hover::before {
	opacity: 1;
}

.sync-option-card.is-selected {
	border-color: #409eff;
	background-color: #f0f9ff;
	transform: translateY(-1px);
	box-shadow: 0 6px 20px rgba(64, 158, 255, 0.2);
}

.sync-option-card.is-selected::before {
	opacity: 1;
}

.option-radio {
	margin-right: 16px;
	z-index: 1;
}

.option-content {
	flex: 1;
	z-index: 1;
}

.option-title {
	font-size: 16px;
	font-weight: 600;
	color: #303133;
	margin-bottom: 4px;
}

.option-description {
	font-size: 14px;
	color: #606266;
	line-height: 1.4;
}

.option-indicator {
	width: 24px;
	height: 24px;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1;
}

/* 日期预览卡片 */
.date-preview-card {
	background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
	border: 1px solid #b3d8ff;
	border-radius: 12px;
	padding: 20px;
	margin-top: 8px;
}

.preview-header {
	display: flex;
	align-items: center;
	margin-bottom: 12px;
}

.preview-title {
	margin-left: 8px;
	font-size: 14px;
	font-weight: 600;
	color: #1890ff;
}

.preview-content {
	padding-left: 32px;
}

.date-range {
	font-size: 16px;
	font-weight: 600;
	color: #0066cc;
	margin-bottom: 8px;
}

.sync-tip {
	display: flex;
	align-items: center;
	font-size: 13px;
	color: #666;
}

.sync-tip span {
	margin-left: 6px;
}

/* 对话框底部 */
.dialog-footer {
	display: flex;
	justify-content: flex-end;
	gap: 12px;
}

/* 动画效果 */
.fade-slide-enter-active,
.fade-slide-leave-active {
	transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-slide-enter-from {
	opacity: 0;
	transform: translateY(-10px) scale(0.95);
}

.fade-slide-leave-to {
	opacity: 0;
	transform: translateY(-10px) scale(0.95);
}

/* 单选按钮样式优化 */
:deep(.sync-option-card .el-radio) {
	margin-right: 0;
}

:deep(.sync-option-card .el-radio__input.is-checked .el-radio__inner) {
	background-color: #409eff;
	border-color: #409eff;
}

:deep(.sync-option-card .el-radio__input.is-checked + .el-radio__label) {
	color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
	:deep(.sync-dialog) {
		width: 90% !important;
		margin: 0 5%;
	}

	.dialog-header {
		padding: 16px 20px;
	}

	.dialog-title {
		font-size: 16px;
	}

	.sync-option-card {
		padding: 14px 16px;
	}

	.option-title {
		font-size: 15px;
	}

	.option-description {
		font-size: 13px;
	}

	.date-preview-card {
		padding: 16px;
	}

	:deep(.sync-dialog .el-dialog__body) {
		padding: 20px;
	}

	:deep(.sync-dialog .el-dialog__footer) {
		padding: 12px 20px;
	}
}

@media (max-width: 480px) {
	.dialog-header {
		flex-direction: column;
		text-align: center;
		padding: 20px;
	}

	.header-icon {
		margin-right: 0;
		margin-bottom: 12px;
	}

	.sync-option-card {
		padding: 12px 14px;
	}

	.dialog-footer {
		flex-direction: column-reverse;
	}

	.dialog-footer .el-button {
		width: 100%;
		margin: 0;
	}

	.dialog-footer .el-button + .el-button {
		margin-bottom: 8px;
	}
}
</style>
